package com.arm.controller.api.upload;

import com.arm.controller.BaseController;
import com.arm.service.ProductEntityService;
import com.arm.tools.result.ResultObj;
import com.arm.tools.result.ReturnCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(description = "文件上传接口")
@RequestMapping("/api/upload")
@RestController
public class APIUploadController extends BaseController {

    @Autowired
    ProductEntityService productEntityService;



    @ApiOperation(value = "图片上传", notes = "图片上传")
    @PostMapping(value = "/uploadImg")
    public String uploadImg(@RequestParam(value = "imageFile", required = false) MultipartFile multipartFiles[]) {
        ResultObj resultObj = new ResultObj();

        String filePath = "autumnrainmorning2/product";
        logger.info(multipartFiles.length+"=====================>>>" + filePath);
        List<String> pathList=new ArrayList<>();
        try {

            //这里可以支持多文件上传
            if (multipartFiles != null && multipartFiles.length >= 1) {
                BufferedOutputStream bw = null;
                try {
                    for (MultipartFile multipartFile : multipartFiles) {
                        String picPath = "";
                        picPath = upLoadFile(multipartFile.getInputStream(), filePath);
                            logger.info("resourceUrl=============>>>" + picPath);
                        pathList.add(picPath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (bw != null) {
                            bw.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }




            resultObj.setData(pathList);
            resultObj.setMsg("操作成功！");
        } catch (Exception e) {
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg("操作失败！");
            e.printStackTrace();
        }
        return resultObj.toJson();
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
}
